const { ipcRenderer } = require("electron");
const minibt = document.querySelector("#minibt");
minibt.addEventListener("click", () => {
    ipcRenderer.send("minimize");
});
const closebt = document.querySelector("#closebt");
closebt.addEventListener("click", () => {
    ipcRenderer.send("close");
});
const videoBox = document.querySelector('#videoBox')
const sdgdvideo = document.querySelector('#sdgdvideo')
const closevideo = document.querySelector('#closevideo')
closevideo.addEventListener('click',()=>{
    videoBox.style.display="none";
    sdgdvideo.src = "";
})

const path =require('path')
let ws
let ip = ""
let jsonData
const fs = require('fs')
function getIpandLink(){
  fs.readFile(path.join(__dirname,'./config.json'),'utf8',(err,data)=>{
    if (err) {
      console.log("读取文件出错：",err);
      return
    }
    jsonData = JSON.parse(data)
    console.log("获取json的消息",jsonData);
    
    ip = jsonData["set_ip"]
    ws = new WebSocket("ws://"+ip+":8002");
    ws.onopen = function (e) {
      console.log("播放端建立websocket链接", e);
      ws.send(JSON.stringify({ "播放端message": "来自播放端" }))
    }
    ws.onmessage = function(message){
    //   console.log(message['data']);
    //   console.log(sdgdvideo.src);
      if (JSON.parse(message['data'])['videoname']=="") {
        videoBox.style.display="none";
        sdgdvideo.src = "";
      }else{
        videoBox.style.display="block";
        sdgdvideo.src = JSON.parse(message['data'])['videoname']
      }
    }
    ws.onclose = function(){
      console.log("播放端ws关闭");
    }
  })
}
getIpandLink()

const bt_set_ip = document.querySelector('#bt_set_ip')
const settings = document.querySelector('#settings')
const ip_input = document.querySelector('#ip_input')
const submitSetting = document.querySelector('#submitSetting')
const closeSetting = document.querySelector('#closeSetting')
function setIpandLink(){
  ws.close();
  
}
bt_set_ip.addEventListener('click',()=>{
  settings.style.display="flex"
  // setIpandLink()
  console.log(jsonData['set_ip']);
  ip_input.value = jsonData['set_ip']
})
submitSetting.addEventListener('click',()=>{
  settings.style.display="none"
  setIpandLink()
  jsonData['set_ip'] = ip_input.value
  console.log("修改后的json：",jsonData);
  
  fs.writeFile(path.join(__dirname,'./config.json'),JSON.stringify(jsonData),'utf8',(err)=>{
    if (err) {
      console.error(err);
    }else{
      console.log("修改ip成功！");
    }
  })
  getIpandLink()
  ip_input.value = ""
})
closeSetting.addEventListener('click',()=>{
  ip_input.value = ""
  settings.style.display="none"
})